#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.contrib.contenttypes import generic
from django.core.exceptions import ObjectDoesNotExist
from django.db import models


class ToReadItem(models.Model):
    """
    A ToReadItem is some kind of internal bookmark where a user maks
    a content object in order to remember to read it some time after.

    Once he has read it, this bookmark will be removed unless archive=True.
    """

    content_type = models.ForeignKey(
        ContentType, verbose_name=_('content type'))
    object_id = models.PositiveIntegerField(_('object id'), db_index=True)
    object = generic.GenericForeignKey('content_type', 'object_id')

    note = models.TextField(_('note'), blank=True, null=True)
    # meaning public or private
    share = models.BooleanField(_('share'), default=False)
    # do not delete after read
    archive = models.BooleanField(_('archive'), default=False) 
    
    adder = models.ForeignKey(
        User, related_name="items_to_read", verbose_name=_('adder'))
    added = models.DateTimeField(_('added'), default=datetime.now)

    class Meta:
        # Enforce unique object association per user
        unique_together = (('user', 'content_type', 'object_id'),)
        verbose_name = _('to-read item')
        verbose_name_plural = _('to-read items')

    def __unicode__(self):
        shared = self.share and _("shared") or _("private")
        archived = self.archive and _("archived") ""
        return u'%s [%s %s]' % (self.object, shared, archived)

    def get_absolute_url(self):
        """
        a shortcut to the object's url
        """
        try:
            return self.get_content_object().get_absolute_url()
        except AttributeError:
            return ""

    def get_object(self):
        """
        """
        try:
            return self.content_type.get_object_for_this_type(pk=self.object_id)
        except ObjectDoesNotExist:
            return None